package com.ljx.rag.rag.service.impl;

import cn.hutool.json.JSONUtil;
import com.ljx.rag.rag.domain.entity.FileVector;
import com.ljx.rag.rag.mapper.FileVectorMapper;
import com.ljx.rag.rag.service.EmbeddingService;
import com.ljx.rag.rag.service.FileService;
import com.ljx.rag.rag.util.FileContentExtractor;
import com.ljx.rag.rag.util.TextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2025-04-07  21:46
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileContentExtractor fileContentExtractor;

    @Autowired
    private EmbeddingService embeddingService;

    @Autowired
    private FileVectorMapper fileVectorMapper;

    @Override
    public void upload(MultipartFile file) {
        try {
            String fileStr = fileContentExtractor.extractContent(file);
            List<String> splitWords = TextUtil.split(fileStr, 200, 50);
            embeddingService.callEmbeddingApi(JSONUtil.toJsonStr(splitWords));
            String vectorStr = tans2Vector(splitWords);
            saveFileVector(file.getOriginalFilename(), fileStr, vectorStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveFileVector(String originalFilename, String content, String vectorStr) {
        fileVectorMapper.insert(new FileVector(originalFilename, content, vectorStr));
    }

    private String tans2Vector(List<String> splitWords) {
        List<BigDecimal> splitStr = embeddingService.callEmbeddingApi(JSONUtil.toJsonStr(splitWords));
        return JSONUtil.toJsonStr(splitStr);
    }
}
